package com.yaorange.teaching.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.yaorange.common.core.utils.DateUtils;
import com.yaorange.common.security.utils.SecurityUtils;
import com.yaorange.teaching.bo.AddInterviewMasteryBo;
import com.yaorange.teaching.domain.YaInterviewMasteryDetail;
import com.yaorange.teaching.mapper.YaInterviewMasteryDetailMapper;
import com.yaorange.teaching.service.IYaInterviewMasteryDetailService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yaorange.teaching.mapper.YaInterviewMasteryMapper;
import com.yaorange.teaching.domain.YaInterviewMastery;
import com.yaorange.teaching.service.IYaInterviewMasteryService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 面试掌握情况记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-11-15
 */
@Service
public class YaInterviewMasteryServiceImpl implements IYaInterviewMasteryService
{
    @Autowired
    private YaInterviewMasteryMapper yaInterviewMasteryMapper;

    @Autowired
    private IYaInterviewMasteryDetailService yaInterviewMasteryDetailService;
    /**
     * 查询面试掌握情况记录
     *
     * @param id 面试掌握情况记录主键
     * @return 面试掌握情况记录
     */
    @Override
    public YaInterviewMastery selectYaInterviewMasteryById(Long id)
    {
        return yaInterviewMasteryMapper.selectYaInterviewMasteryById(id);
    }

    /**
     * 查询面试掌握情况记录列表
     *
     * @param yaInterviewMastery 面试掌握情况记录
     * @return 面试掌握情况记录
     */
    @Override
    public List<YaInterviewMastery> selectYaInterviewMasteryList(YaInterviewMastery yaInterviewMastery)
    {
        return yaInterviewMasteryMapper.selectYaInterviewMasteryList(yaInterviewMastery);
    }

    /**
     * 新增面试掌握情况记录
     *
     * @param yaInterviewMastery 面试掌握情况记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertYaInterviewMastery(AddInterviewMasteryBo yaInterviewMastery)
    {
        List<String> selectedInterviewList = yaInterviewMastery.getSelectedInterviewList();

        //先计算出每个面试题的得分
        //key:interviewId  value:选项（2，3）
        Map<Long, Set<Integer>> interviewSelectedItemMap = getLongSetMap(selectedInterviewList);

        //再计算所有面试题平均分
        //key:interviewId  value:score
        Map<Long, Integer> scoreMap = interviewSelectedItemMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> computeScore(e.getValue())));

        //计算map中value的平均分
        long avgScore = (long) scoreMap.values().stream().mapToInt(Integer::intValue).average().orElse(0);

        //1.新增面试记录(1方)
            //维护冗余字段 技能平均分
        yaInterviewMastery.setAvgScore(avgScore);
        yaInterviewMastery.setCommunicationScore(yaInterviewMastery.getCommunicationMastery().split(",").length);
        yaInterviewMastery.setCreateTime(new Date());
        yaInterviewMastery.setCreateBy(SecurityUtils.getUsername());
        yaInterviewMasteryMapper.insertYaInterviewMastery(yaInterviewMastery);

        Long interviewMasteryId = yaInterviewMastery.getId();

        //2.新增面试记录详情(多方-维护外键)
        List<YaInterviewMasteryDetail> detailList = getYaInterviewMasteryDetails(yaInterviewMastery, interviewSelectedItemMap, scoreMap, interviewMasteryId);
        yaInterviewMasteryDetailService.saveBatch(detailList,100);
        return 1;
    }

    /**
     * 生成面试记录详情列表
     * @param yaInterviewMastery
     * @param map
     * @param scoreMap
     * @param interviewMasteryId
     * @return
     */
    private static List<YaInterviewMasteryDetail> getYaInterviewMasteryDetails(AddInterviewMasteryBo yaInterviewMastery, Map<Long, Set<Integer>> map, Map<Long, Integer> scoreMap, Long interviewMasteryId) {
        List<YaInterviewMasteryDetail> detailList = map.entrySet().stream().map(entry -> {
            Long interviewId = entry.getKey();
            Set<Integer> selectedItem = entry.getValue();
            YaInterviewMasteryDetail detail = new YaInterviewMasteryDetail();
            detail.setQuestionId(interviewId);
            //将set中的元素转成  1,2,3
            detail.setDegree(selectedItem.stream().map(String::valueOf).collect(Collectors.joining(",")));
            detail.setScore(scoreMap.get(interviewId));
            detail.setUserId(yaInterviewMastery.getUserId());
            detail.setInterviewMasteryId(interviewMasteryId);
            detail.setCreateTime(yaInterviewMastery.getCreateTime());
            return detail;
        }).collect(Collectors.toList());
        return detailList;
    }

    private static Map<Long, Set<Integer>> getLongSetMap(List<String> selectedInterviewList) {
        Map<Long, Set<Integer>> map = new HashMap<>();
        selectedInterviewList.forEach(item->{
            //1,2
            String[] split = item.split(",");
            Long interviewId = Long.valueOf(split[0]);
            Integer selectedItem = Integer.valueOf(split[1]);
            //判断当前map中是否存在该面试题记录
            Set<Integer> selectedItems = map.get(interviewId);
            if (CollectionUtils.isEmpty(selectedItems)) {
                //不存在，说明是第一次添加，新建一个空的set
                selectedItems = new HashSet<>();
                selectedItems.add(selectedItem);
                map.put(interviewId, selectedItems);
            } else {
                //存在，直接添加
                selectedItems.add(selectedItem);
            }
        });
        return map;
    }


    private Integer computeScore(Set<Integer> set) {
       //1->0分   2->1    3,4,5,6,7->2
        int result = 0;
        for (Integer item : set) {
            if (item.equals(1)) {
                return 0;
            }
            else if (item.equals(2)) {
                return 1;
            }
            else {
                result += 2;
            }
        }
        return result;
    }

    /**
     * 修改面试掌握情况记录
     *
     * @param yaInterviewMastery 面试掌握情况记录
     * @return 结果
     */
    @Override
    public int updateYaInterviewMastery(YaInterviewMastery yaInterviewMastery)
    {
        yaInterviewMastery.setUpdateTime(DateUtils.getNowDate());
        return yaInterviewMasteryMapper.updateYaInterviewMastery(yaInterviewMastery);
    }

    /**
     * 批量删除面试掌握情况记录
     *
     * @param ids 需要删除的面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteYaInterviewMasteryByIds(Long[] ids)
    {
        return yaInterviewMasteryMapper.deleteYaInterviewMasteryByIds(ids);
    }

    /**
     * 删除面试掌握情况记录信息
     *
     * @param id 面试掌握情况记录主键
     * @return 结果
     */
    @Override
    public int deleteYaInterviewMasteryById(Long id)
    {
        return yaInterviewMasteryMapper.deleteYaInterviewMasteryById(id);
    }
}
